﻿#include "logger\WindowSink.h"

#include <windows.h>  // 只在 .cpp 文件中包含平台相关的头文件

#include <mutex>
#include <queue>

namespace Logging {
class WindowSink::Impl {
 public:
  explicit Impl(NativeWindowHandle target_handle)
      : target_hwnd_(static_cast<HWND>(target_handle)) {}

  void Log(const LogMessageInfo& message) {
    {
      std::lock_guard<std::mutex> lock(queue_mutex_);
      log_queue_.push(message);
    }
    // 使用 PostMessage 进行线程安全的消息投递
    if (target_hwnd_ && IsWindow(target_hwnd_)) {
      PostMessage(target_hwnd_, WM_SINK_LOG_READY, 0, 0);
    }
  }

  void DrainTo(std::queue<LogMessageInfo>& target_queue) {
    std::lock_guard<std::mutex> lock(queue_mutex_);
    if (!log_queue_.empty()) {
      log_queue_.swap(target_queue);
    }
  }

 private:
  HWND target_hwnd_;
  std::mutex queue_mutex_;
  std::queue<LogMessageInfo> log_queue_;
};

// --- WindowSink 公共接口实现 ---
WindowSink::WindowSink(NativeWindowHandle target_handle)
    : pimpl_(std::make_unique<Impl>(target_handle)) {}
WindowSink::~WindowSink() = default;  // 定义析构函数

void WindowSink::Log(const LogMessageInfo& message) { pimpl_->Log(message); }

void WindowSink::DrainTo(std::queue<LogMessageInfo>& target_queue) {
  pimpl_->DrainTo(target_queue);
}
}  // namespace Logging